package com.tz.tzgw.pc.web;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.crypto.SecureUtil;
import com.tz.tzgw.pc.web.annotation.AdminControllerAnnotation;
import com.tz.tzgw.pc.web.dao.*;
import com.tz.tzgw.pc.web.model.Member;;
import com.tz.tzgw.pc.web.model.MemberRole;
import com.tz.tzgw.pc.web.model.Role;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


@Controller
@AdminControllerAnnotation
@RequestMapping("/api/")
public class AdminController {
    private final MemberDao memberDao;

    private final MemberRoleDao memberRoleDao;

    private final RoleDao roleDao;
    private final RoleMenuDao roleMenuDao;


    private final MenuDao menuDao;

    private final ResourceLoader resourceLoader;


    public AdminController(MemberDao memberDao, MemberRoleDao memberRoleDao,RoleDao roleDao,RoleMenuDao roleMenuDao,MenuDao menuDao,ResourceLoader resourceLoader) {
        this.memberDao = memberDao;
        this.memberRoleDao = memberRoleDao;
        this.roleDao = roleDao;
        this.roleMenuDao = roleMenuDao;
        this.menuDao = menuDao;
        this.resourceLoader = resourceLoader;
    }
    @RequestMapping("do_login")
    @ResponseBody
    public SaResult do_login(@RequestBody Map<String, String> requestBody,HttpSession session) {
        String username = requestBody.get("username");
        String password = requestBody.get("password");
        String code = requestBody.get("code");

        // 检查 username 是否为空
        if (username == null || username.trim().isEmpty()) {
            return SaResult.error("用户名必填");
        }

        // 检查 password 是否为空
        if (password == null || password.trim().isEmpty()) {
            return SaResult.error("密码必填");
        }

        // 检查 code 是否为空
        if (code == null || code.trim().isEmpty()) {
            return SaResult.error("验证码必填");
        }

        String storedCode = (String) session.getAttribute("code");
        // 检查验证码是否匹配
        if (!code.equalsIgnoreCase(storedCode)) {
            return SaResult.error("验证码错误");
        }
        Member member = memberDao.getUserByUsername(username);
        if (member != null) {
            String res1 = SecureUtil.md5(password);
            if (res1.equals(member.getPassword())){
                StpUtil.login(member.getId());
                return SaResult.data(StpUtil.getTokenValue());
            }else{
                return SaResult.error("密码错误");
            }
        } else {
            // 用户不存在，返回错误信息
            return SaResult.error("用户不存在");
        }
    }
    @RequestMapping("user_info")
    @ResponseBody
    @SaCheckLogin
    public SaResult user_info() {
        String member_id = (String) StpUtil.getLoginId();
        Member member = memberDao.getUserById(member_id);
        if (member != null) {
            MemberRole memberRole =  memberRoleDao.getRoleIdByMemberId(member.getId());

            Role role =  roleDao.getRoleById(memberRole.getRoleId());
            String[] permissions = new String[1];
            if (role != null && role.getRoleKey().equals("superadmin")){
                permissions[0] = "*:*:*";
            }else{
                Long[] roleMenu =  roleMenuDao.getMenuIdsForRoleId(memberRole.getRoleId());
                permissions = menuDao.getPermssByMenuIds(roleMenu);
            }
            Map<String, Object> data = new HashMap<>();
            data.put("user", member);
            data.put("roles", role);
            data.put("permissions", permissions);
            return SaResult.data(data);

        } else {
            // 用户不存在，返回错误信息
            return SaResult.error("用户不存在");
        }
    }


    /**
     * 生成验证码
     * @return SaResult
     * @throws Exception
     */
    @RequestMapping("get_code")
    @ResponseBody
    public SaResult getCode(HttpSession session) {
        // HuTool定义图形验证码的长和宽,验证码的位数，干扰线的条数
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(116, 36, 4, 10);
        // 将验证码放入session
        session.setAttribute("code", lineCaptcha.getCode());
        System.out.println(lineCaptcha.getCode());

        // 将验证码图片转换为Base64编码的字符串
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        lineCaptcha.write(outputStream);
        byte[] imageBytes = outputStream.toByteArray();
        String base64Image = Base64.getEncoder().encodeToString(imageBytes);

        Map<String, String> data = new HashMap<>();
        data.put("img", "data:image/png;base64," + base64Image);
        return SaResult.data(data);
    }


    @SaCheckLogin
    @ResponseBody
    @RequestMapping("/upload_file")
    public SaResult upload_file(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return SaResult.error("上传失败，请选择文件");
        }
        try {
            // 获取静态资源的路径
            String uploadDir = resourceLoader.getResource("classpath:/static/uploads/").getFile().getAbsolutePath();

            // 获取当前日期并格式化为需要的字符串形式
            LocalDate currentDate = LocalDate.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
            String dateStr = currentDate.format(formatter);

            // 自定义文件名，防止重名
            String extension = StringUtils.getFilenameExtension(file.getOriginalFilename());
            String fileName = UUID.randomUUID().toString() + "." + extension;

            // 创建目录（如果不存在）
            Path directoryPath = Paths.get(uploadDir, dateStr);
            Files.createDirectories(directoryPath);

            // 目标文件路径
            Path destPath = Paths.get(directoryPath.toString(), fileName);

            // 保存文件
            file.transferTo(destPath.toFile());
            return SaResult.data(dateStr+"/"+fileName);
        } catch (IOException e) {
            return SaResult.error("上传失败");
        }
    }
}
